﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DataLib.Accounts.Bus;
using System.Web.Script.Serialization;
using DataLib.BLL;
using DataLib.Model;

namespace Ewts.ashx
{
    /// <summary>
    /// Inwrl 的摘要说明
    /// </summary>
    public class Inwrl : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            JavaScriptSerializer serializer = new JavaScriptSerializer();

              string result = "";
            //barcode islocak修改
            if (context.Request["barcodeid"]!=null && context.Request["barcodeid"].ToString().Trim() != "")
            {
                string id = "";
                string islock = "";
                id = context.Request["id"].ToString().Trim();
                if (context.Request["islock"].ToString().Trim() != "")
                {
                    islock = context.Request["islock"].ToString().Trim();
                }

                DataLib.Model.BarCode barcode = new DataLib.BLL.BarCode().GetModel(Convert.ToInt32(id));
                if (islock == "1")
                {
                    barcode.isLocak = true;
                    result = "已锁定";
                }
                else
                {
                    barcode.isLocak = false;
                    result = "取消锁定";
                }

                if ((new DataLib.BLL.BarCode().Update(barcode)) == true)
                    result += "成功！";
                else
                    result += "失败！";
            }

            if (context.Request["delbarid"] != null && context.Request["delbarid"].ToString().Trim() != "")
            {
                //删除barCode
                result = deleteByid(context.Request["delbarid"].ToString().Trim());
            }
            else if (context.Request["barid"] != null && context.Request["barid"].ToString().Trim() != "")
            {
                //
                result = GetJsonByBarid(int.Parse(context.Request["barid"].ToString().Trim()));
            }
            //修改机械误差
            else if(context.Request["mec"]!=null && context.Request["mec"].ToString().Trim()!="")
            {
                int wrlid = int.Parse(context.Request["hidInStoID"].ToString());
                DataLib.BLL.InStorage bllin = new DataLib.BLL.InStorage();
                DataLib.Model.InStorage insmodel = new DataLib.Model.InStorage();
                if (wrlid == 0)
                {
                    insmodel = AddInStorage(context);
                    result = serializer.Serialize(insmodel);
                }
                else
                {
                    insmodel  = bllin.GetModel(wrlid);
                    insmodel.mechanerr = decimal.Parse(context.Request["mec"].ToString().Trim());
                    bllin.Update(insmodel);
                    DataLib.BLL.OutStorage outbll = new DataLib.BLL.OutStorage();
                    DataLib.Model.OutStorage outmodel = new DataLib.Model.OutStorage();
                    outmodel = outbll.GetModel((int)insmodel.outid);
                    decimal instotalweiht = 0;
                    instotalweiht = bllin.GetInsTotalWeight(wrlid);
                    if (instotalweiht + insmodel.mechanerr == outmodel.totalWeight)
                    {
                        outmodel.status = 0;
                    }
                    else
                    {
                        outmodel.status = 3;
                    }
                    outbll.Update(outmodel);




                    //2015年5月17日 FIFA
                        
                        if (!string.IsNullOrEmpty(insmodel.vloadnum))
                        {
                            //2015年5月17日  FIFI
                            /////////////////////////////////////
                            DataLib.Model.LoadNum loadnumentity = new DataLib.Model.LoadNum();
                            DataLib.BLL.LoadNum _loadbll = new DataLib.BLL.LoadNum();
                            loadnumentity = _loadbll.GetModelList(" loadnum = '" + insmodel.vloadnum + "'").ElementAtOrDefault(0); ;
                            if (loadnumentity != null && loadnumentity.id > 0)
                            {
                                loadnumentity.totalWeight -= insmodel.mechanerr;
                                _loadbll.Update(loadnumentity);
                            }

                            /////////////////////////////////////
                        }
                    


                    result = "0";
                }

            }
            else
            {
                //插入记录
                DataLib.BLL.InStorage bllIn = new DataLib.BLL.InStorage();
                DataLib.Model.InStorage inModel = new DataLib.Model.InStorage();

                //验证重量是否超重

                //入库单操作，第一次就新增，否则读取传过来的入库单，绑定入库单号

                if (context.Request["hidInStoID"] != null && context.Request["hidInStoID"].ToString().Trim() == "0")
                {

                    inModel = AddInStorage(context);
                }
                else
                {
                    string instoid = context.Request["hidInStoID"].ToString().Trim();
                    inModel = bllIn.GetModel(int.Parse(instoid));
                }

                decimal curtotal = 0;
                decimal outtotal = 0;
                bool flag = true;


                //barcode重量
                curtotal = bllIn.GetInsTotalWeight((int)inModel.id);
               
                if (context.Request["parid"] != null && context.Request["parid"].ToString().Trim() != "0")
                {
                    DataLib.Model.OutStorage outmodel = new DataLib.BLL.OutStorage().GetModel(int.Parse(context.Request["parid"].ToString().Trim()));
                    outtotal = (decimal)outmodel.totalWeight;
                    if(context.Request["jxwc"]!=null && context.Request["jxwc"].ToString()!="")
                        curtotal = curtotal + decimal.Parse(context.Request["jxwc"].ToString());
                    ////outtype = outmodel.outStorageType;
                }
                if (context.Request["nwt"] != null)
                {
                    decimal barnwt = decimal.Parse(context.Request["nwt"].ToString().Trim());
                    curtotal += barnwt;

                    
                if ((outtotal != 0) && (curtotal > outtotal))
                    {
                        flag = false;
                    }


                    if (flag == true)
                    {
                        //入库明细
                        DataLib.Model.BarCode barModel = new DataLib.Model.BarCode();
                        barModel = GetBarCode(context, inModel);
                        result += serializer.Serialize(barModel);
                    }

                }

                if (flag == true)
                {
                    result += ",";
                    result += serializer.Serialize(inModel);
                    result = "[" + result + "]";
                }
                else
                {
                    result = "CZ";
                }

            }
    
            context.Response.Write(result);
        }

        /// <summary>
        /// 添加新的入库单
        /// </summary>
        public DataLib.Model.InStorage AddInStorage(HttpContext context)
        {
            DataLib.Model.InStorage inModel = new DataLib.Model.InStorage();
            
            //2015年5月17日 FIFA
            string outvloadnum = "";
            ////////

            if (context.Request["oper"] != null)
            {
                inModel.Operator = context.Request["oper"].ToString().Trim();
            }
            if (context.Request["alllock"] != null && context.Request["alllock"].ToString().Trim() != "")
            {
                inModel.islock = Boolean.Parse(context.Request["alllock"].ToString());
            }
            if (context.Request["inDepart"] != null && context.Request["inDepart"].ToString().Trim() != "")
            {
                inModel.InDepart = context.Request["inDepart"].ToString().Trim();
            }
            if (context.Request["outDepart"] != null && context.Request["outDepart"].ToString().Trim() != "")
            {
                inModel.OutDepart = context.Request["outDepart"].ToString().Trim();
            }
            if (context.Request["month"] != null && context.Request["month"].ToString().Trim().Length == 6)
            {
                inModel.clearingmonth = context.Request["month"].ToString().Trim();
            }
            inModel.instoragetime = DateTime.Now;
            inModel.status = 0;

            if (context.Request["jxwc"] != null && context.Request["jxwc"].ToString().Trim() != "")
            {
                inModel.mechanerr = decimal.Parse(context.Request["jxwc"].ToString().Trim());
            }

            if (context.Request["mec"] != null && context.Request["mec"].ToString().Trim() != "")
            {
                inModel.mechanerr = decimal.Parse(context.Request["mec"].ToString().Trim()); ;
            }

            inModel.cjoid = int.Parse(getObjTostring(context.Request["cjoid"], "0"));

            if (context.Request["parid"] != null && context.Request["parid"].ToString().Trim() != "0")
            {
                inModel.outid = int.Parse(context.Request["parid"].ToString().Trim());
                DataLib.Model.OutStorage oModel = new DataLib.BLL.OutStorage().GetModel((int)inModel.outid);
                outvloadnum = oModel.VLoadNum;
            }
            else
            {
                inModel.outid = 0;
            }
            if (context.Request["loadnumid"] != null && context.Request["loadnumid"].ToString().Trim() != "")
            {
                string loadnum = "";
                string loadnumid = context.Request["loadnumid"].ToString().Trim();
                if (loadnumid != "0")
                {
                    //2015年5月17日  FIFI
                    /////////////////////////////////////
                    DataLib.Model.LoadNum loadnumentity = new DataLib.Model.LoadNum();
                    DataLib.BLL.LoadNum _loadbll = new DataLib.BLL.LoadNum();
                    loadnumentity = _loadbll.GetModel(int.Parse(loadnumid));
                    if (loadnumentity != null && loadnumentity.id > 0)
                    {
                        loadnum = loadnumentity.loadnum;
                            loadnumentity.totalWeight -=inModel.mechanerr;
                        _loadbll.Update(loadnumentity);
                        inModel.loadnumid = loadnumentity.id;
                    }
                    /////////////////////////////////////

                    //这行是原来的代码
                    //loadnum = new DataLib.BLL.LoadNum().GetModel(int.Parse(loadnumid)).loadnum;

                }
                else
                {
                   // loadnum = getObjTostring(context.Request["vload"]);
                  
                    //2015年5月17日  FIFI
                    /////////////////////////////////////
                    DataLib.Model.LoadNum loadnumentity = new DataLib.Model.LoadNum();
                    DataLib.BLL.LoadNum _loadbll = new DataLib.BLL.LoadNum();
                    loadnumentity = _loadbll.GetModelList(" loadnum = '" + outvloadnum + "'").ElementAtOrDefault(0);
                    if (loadnumentity != null && loadnumentity.id > 0)
                    {
                        loadnum = loadnumentity.loadnum;
                        loadnumentity.totalWeight-= inModel.mechanerr;
                        _loadbll.Update(loadnumentity);
                        inModel.loadnumid = loadnumentity.id;
                    }

                    
                    /////////////////////////////////////
                }
                inModel.vloadnum = loadnum;
            }
            string wrlno = "";
            string intype = "";
            wrlno = Code.NumGeneration.GetSerialNum("M", "WRL");
            inModel.wrlno = wrlno;


            inModel.id = new DataLib.BLL.InStorage().Add(inModel);
            return inModel;

        }

        /// <summary>
        /// 添加barcode并返回barcode的实体对象
        /// </summary>
        /// <param name="context"></param>
        /// <param name="inModel"></param>
        /// <returns></returns>
        public DataLib.Model.BarCode GetBarCode(HttpContext context, DataLib.Model.InStorage inModel)
        {


            string loadnumid = null;
            string loadnum = "";

            if (context.Request["loadnumid"] != null && context.Request["loadnumid"].ToString().Trim() != "")
            {

                loadnumid = context.Request["loadnumid"].ToString().Trim();
                if (loadnumid != "0")
                {
                    loadnum = new DataLib.BLL.LoadNum().GetModel(int.Parse(loadnumid)).loadnum;
                }
                else
                {
                    loadnum = getObjTostring(context.Request["vload"]);
                }
            }



            string strtemp = null;



            DataLib.Model.BarCode bmodel = new DataLib.Model.BarCode();
            bmodel.cjoid = int.Parse(getObjTostring(context.Request["cjoid"], "0"));
            if (loadnumid != null)
                bmodel.loadnumid = int.Parse(loadnumid);
            else
                bmodel.loadnumid = 0;
            strtemp = getObjTostring(context.Request["loadnumid"]);
            if (strtemp != null)
                bmodel.loadnumid = int.Parse(strtemp);
            else
                bmodel.loadnumid = 0;


            bmodel.comeunder = getObjTostring(context.Request["comeunder"]);


            bmodel.gwt = decimal.Parse(getObjTostring(context.Request["gwt"], "0"));

            bmodel.nwt = decimal.Parse(getObjTostring(context.Request["nwt"], "0"));

            bmodel.tare1 = decimal.Parse(getObjTostring(context.Request["tare1"], "0"));

            bmodel.tare2 = decimal.Parse(getObjTostring(context.Request["tare2"], "0"));

            bmodel.barbelong = context.Request["inDepart"].ToString();      //归属地
            bmodel.bargraphic = context.Request["outDepart"].ToString();     //处理地
            bmodel.qty = int.Parse(getObjTostring(context.Request["qty"], "0"));
            strtemp = getObjTostring(context.Request["islocak"]);
            if (strtemp != "")
                bmodel.isLocak = true;
            else
                bmodel.isLocak = false;

            bmodel.storageid = int.Parse(getObjTostring(context.Request["storageid"], "0"));
            bmodel.stroageNo = getObjTostring(context.Request["storageno"]);
            bmodel.packageno = getObjTostring(context.Request["packageno"]);
            bmodel.rdh = getObjTostring(context.Request["rdh"]);
            bmodel.remark = getObjTostring(context.Request["remark"]);
            bmodel.InStrorageID = inModel.id;
            bmodel.status = -1;
            bmodel.goodsid = getNumberByobj(context.Request["goodsid"]);
            bmodel.goodscode = getObjTostring(context.Request["goodscode"]);
            bmodel.goodsname = getObjTostring(context.Request["goodsname"]);
            bmodel.rubbishcode = getObjTostring(context.Request["rcode"]);
            bmodel.rubbishtype = getObjTostring(context.Request["rname"]);
            bmodel.plateid = getNumberByobj(context.Request["plateid"]);
            bmodel.plateno = getObjTostring(context.Request["plateno"]);
            bmodel.boxcount = getNumberByobj(context.Request["boxamount"]);


            if (context.Request["parid"] != null && context.Request["parid"].ToString().Trim() != "")
            {
                bmodel.ParmentID = int.Parse(context.Request["parid"].ToString().Trim());
            }
            else
                bmodel.ParmentID = 0;

            if (loadnumid != "0")
                bmodel.loadnumv = loadnum;
            else
            {
                if (bmodel.ParmentID != 0)
                {
                    DataLib.Model.OutStorage outModel = new DataLib.BLL.OutStorage().GetModel((int)bmodel.ParmentID);
                    bmodel.loadnumv = outModel.VLoadNum;
                }
            }

            if (context.Request["barcode"] != null && context.Request["barcode"].ToString().Trim() != "")
            {
                bmodel.barcodevalue = context.Request["barcode"].ToString().Trim();
            }
            else
            {
                bmodel.barcodevalue = Code.NumGeneration.GetSerialNum(bmodel.loadnumv + inModel.wrlno + bmodel.goodscode.PadRight(10, '0'), "BarCode");
            }


            bmodel.id = new DataLib.BLL.BarCode().Add(bmodel);
            return bmodel;

        }

        //根据id修改称重的信息
        protected string deleteByid(string id)
        {
            string result = "";
            //barcode
            DataLib.Model.BarCode barcodeModel = new DataLib.BLL.BarCode().GetModel(Convert.ToInt32(id));
            //loadnum
            DataLib.Model.LoadNum loadnumModel = new DataLib.BLL.LoadNum().GetModel(Convert.ToInt32(barcodeModel.loadnumid));
            //outstorage
            DataLib.Model.OutStorage outstorageModel = new DataLib.BLL.OutStorage().GetModel(Convert.ToInt32(barcodeModel.OutStrorageID));

            switch (barcodeModel.status)
            {
                case -1:
                    new DataLib.BLL.BarCode().Delete(Convert.ToInt32(id));
                    result = "删除成功！";
                    break;
                case 1:
                    loadnumModel.totalWeight -= barcodeModel.nwt;   //临时库入库  
                    new DataLib.BLL.LoadNum().Update(loadnumModel);         //更新loadnum表
                    barcodeModel.isdel_out = -1;                    //修改barcode的删除状态
                    new DataLib.BLL.BarCode().Update(barcodeModel);
                    result = "删除成功！";
                    break;
                case 2:
                case 4:
                case 6:             //不可删除
                case 8:
                case 10:
                    result = "已出库不可删除！";
                    break;
                case 3:
                    loadnumModel.finishWeight -= barcodeModel.nwt;  //load单已称重修改
                    new DataLib.BLL.LoadNum().Update(loadnumModel);         //更新loadnum表

                    outstorageModel.currentWeight -= barcodeModel.nwt;  //出库单修改currentweight重量
                    new DataLib.BLL.OutStorage().Update(outstorageModel);       //更新出库单数据

                    barcodeModel.isdel_out = -1;                        //修改barcode的删除状态
                    new DataLib.BLL.BarCode().Update(barcodeModel);
                    result = "删除成功！";
                    break;
                case 5:
                case 7:
                case 9:
                    outstorageModel.currentWeight -= barcodeModel.nwt;  //出库单修改currentweight重量
                    new DataLib.BLL.OutStorage().Update(outstorageModel);       //更新出库单数据
                    barcodeModel.isdel_out = -1;                        //修改barcode的删除状态
                    new DataLib.BLL.BarCode().Update(barcodeModel);
                    result = "删除成功！";
                    break;
                default:
                    result = "不合法！";
                    break;
            }

            return result;
        }

        public string GetJsonByBarid(int barid)
        {
            string strjson = "";
            DataLib.Model.BarCode bar = new DataLib.BLL.BarCode().GetModel(barid);
            if (bar != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                strjson = serializer.Serialize(bar);
            }
            return strjson;
        }

        /// <summary>
        /// 当字符串为空 返回默认的值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public string getObjTostring(object obj, string def)
        {
            string str = getObjTostring(obj);
            if (str == "")
                str = def;
            return str;
        }

        /// <summary>
        /// 当对象为空，返回0
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int getNumberByobj(object obj)
        {
            if (obj != null && obj.ToString().Trim() != "")
                return int.Parse(obj.ToString());
            else
                return 0;
        }

        /// <summary>
        /// 当对象为空返回 "" 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string getObjTostring(object obj)
        {
            if (obj != null && obj.ToString().Trim() != "")
                return obj.ToString().Trim();
            else
                return "";
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public DataLib.Model.InStorage UpdateMec(HttpContext context) 
        {
            //插入记录
            DataLib.Model.InStorage inModel = new DataLib.Model.InStorage();
            inModel = AddInStorage(context);
            return inModel;
        }
    }
}